<template>
  <div class="chat">
    <!-- <Scroll
      class="chat-body"
      :class="height"
      :data="chatMsgList.length"
      :scrollToEndFlag="true"
      ref="msg-box"
    > -->
    <div class="chat-body">
      <div class="bs">
        <div v-for="(chat, index) in chatMsgList" :key="index" class="imgbox">
          <!-- 客户 -->
          <div v-if="chat.from_user != params.from_user" class="chat-one">
            <img class="chat-face" :src="store.state.user.clientInfo.avatar" />
            <div class="chat-box">
              <div class="chat-content" v-if="chat.msg_type == '1'">
                {{ chat.content }}
                <span class="right_triangle"></span>
              </div>
              <div class="img-box" v-if="chat.msg_type == '2'">
                <!-- <img
                  class="chat-img"
                  v-if="chat.msg_type == '2'"
                  @click="showImg(chat.content)"
                  :src="chat.content"
                /> -->
                <el-image
                  fit="cover"
                  :preview-src-list="[chat.content]"
                  :src="chat.content"
                />
              </div>
              <Audio
                :src="chat.content"
                v-model="isRight"
                v-if="chat.msg_type == '4'"
              ></Audio>
            </div>
          </div>
          <!-- 医生 -->
          <div v-else class="chat-one chat-one-mine">
            <div class="chat-box">
              <div
                class="chat-content"
                style="background: #6ebe89"
                v-if="chat.msg_type == '1'"
              >
                {{ chat.content }}
                <span class="left_triangle"></span>
              </div>
              <div class="img-box" v-if="chat.msg_type == '2'">
                <el-image
                  fit="cover"
                  :preview-src-list="[chat.content]"
                  :src="chat.content"
                />
              </div>
              <!-- msg4 chat.content-->
              <Audio1
                :src="chat.content"
                v-if="chat.msg_type == '4'"
                v-model="isRight"
              ></Audio1>
              <div class="rx-box bs" v-if="chat.msg_type == '5'">
                <p class="fz-12 mb-5">
                  开方人：{{ JSON.parse(chat.content).doctor_name }}
                </p>

                <div class="header flex">
                  <div class="left mr-5">
                    <img src="@/assets/img/icon/home/rx.png" alt="" />
                  </div>
                  <div class="right fz-10" style="color: #1f1f1f">
                    <p>{{ JSON.parse(chat.content).title }}</p>
                    <p>
                      价格：<span style="color: #f60707"
                        >￥{{ JSON.parse(chat.content).price }}</span
                      >
                    </p>
                    <p>开方时间：{{ JSON.parse(chat.content).time }}</p>
                  </div>
                </div>
                <!-- <p class="text-center mt-10" style="color: #f60707">点击购买</p> -->
              </div>
            </div>
            <img class="chat-face" :src="store.state.user.userInfo.avatar" />
          </div>
        </div>
      </div>
    </div>
    <div class="utils">
      <img src="@/assets/img/icon/home/tupian.svg" alt="" />
    </div>
    <el-input type="textarea" v-model="content" placeholder="请输入消息" />
    <div class="footer-btn flex flex-end">
      <el-button style="background: #07c160; color: #fff" @click="sendmsg"
        >发送</el-button
      >
    </div>
    <!-- </Scroll> -->
  </div>
</template>

<script lang="ts">
import { ref, defineComponent, computed, onUnmounted, onMounted } from 'vue'
import Audio from '@/components/Audio.vue'
import Audio1 from '@/components/Audio.vue'

import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { socketParams } from '../type'
export default defineComponent({
  name: 'chat',
  components: {
    Audio,
    Audio1
  },
  setup() {
    const store = useStore()
    const patient = store.state.user.clientInfo
    const user = store.state.user.userInfo
    const chatMsgList = computed(() => store.state.message.message)
    let wsUrl = process.env.VUE_APP_WS_URL
    let content = ref('')
    let isRight = ref(false)
    let lockReconnect = false // 避免重复连接
    let wsSocket: WebSocket
    let timeoutObj: number
    let isClose = false
    let timeout = 30000
    const params = {
      from_user: user.doctor_no,
      to_user: patient.patient_id
    }
    /**
     * 公共发送消息方法
     */
    const commonSent = (ajaxparams: socketParams, callback: () => void) => {
      if (wsSocket.readyState == WebSocket.OPEN) {
        wsSocket.send(JSON.stringify(ajaxparams))
        callback()
      } else {
        ElMessage.error('发送失败')
      }
    }
    /**
     * 初始化websocket
     */
    const createWebSocket = () => {
      try {
        if ('WebSocket' in window) {
          // socket读取
          socketGetMsgList()
        } else if ('MozWebSocket' in window) {
          socketGetMsgList()
        } else {
          ElMessage.error('链接失败，请稍后再试！')
        }
      } catch (error) {
        reconnect()
      }
    }
    /**
     * 心跳检测
     */
    const start = () => {
      clearTimeout(timeoutObj)
      timeoutObj = setTimeout(() => {
        wsSocket.send('ping')
      }, timeout)
    }
    /**
     * 失败重连
     */
    const reconnect = () => {
      if (lockReconnect) return
      lockReconnect = true
      setTimeout(() => {
        createWebSocket()
        lockReconnect = false
      }, 2000)
    }
    /**
     *socket方式读取
     */
    const socketGetMsgList = () => {
      wsSocket = new WebSocket(wsUrl)
      wsSocket.onopen = (event) => {
        console.log(event, '链接成功')
        let ajaxParams = {
          ...params,
          msg_type: 'bind'
        }
        wsSocket.send(JSON.stringify(ajaxParams))
        start()
      }
      wsSocket.onerror = (event) => {
        // if (!this.isPro) console.log('error ...', event)
        console.log(event, '链接失败')

        reconnect()
      }
      wsSocket.onclose = (event) => {
        // if (!this.isPro) console.log('close ...', event)
        console.log(event, '链接关闭')
        if (!isClose) reconnect()
      }
      wsSocket.onmessage = (event) => {
        const resData = JSON.parse(event.data)
        if (resData.msg_type > 0) {
          chatMsgList.value.push(resData)
        }

        start()
      }
    }
    /**
     * 关闭socket
     */
    const closeSocket = () => {
      isClose = true
      clearTimeout(timeoutObj)
      if (wsSocket) wsSocket.close()
    }
    /**
     * 发送消息
     */
    const sendmsg = () => {
      if (content.value.trim() != '') {
        let ajaxParams = {
          ...params,
          msg_type: 1,
          to_user: patient.patient_id,
          content: content.value
        }
        commonSent(ajaxParams, () => {
          content.value = ''
        })
      }
    }
    onMounted(() => {
      createWebSocket()
    })
    onUnmounted(() => {
      closeSocket()
    })
    return {
      chatMsgList,
      isRight,
      store,
      patient,
      content,
      params,
      sendmsg
    }
  }
})
</script>

<style lang="less" scoped>
.chat {
  height: 100%;
}
.container {
  background-color: #f1f1f1;
  // max-height: 100vh;
  // padding-bottom: 100px;
  height: 682px;
  overflow-y: scroll;
}
// ios
.height1 {
  height: 482px;
}
.height2 {
  height: 498px;
}

.chat-body {
  // padding-bottom: 178/2px;
  // height: 498px;
  &::-webkit-scrollbar {
    width: 0 !important;
  }
  height: 682px;
  overflow-y: scroll;
  .chat-time {
    text-align: center;
    color: #888;
    padding: 20px 0 0;
  }
  .chat-one {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: flex-start;
    padding: 10px 0;
  }
  .chat-one-begin {
    padding: 20px 0 0;
  }
  .chat-one-mine {
    justify-content: flex-end;
  }
  .chat-face {
    width: 42px;
    height: 42px;
    border-radius: 5px;
    margin-left: 20px;
  }
  .chat-one-mine .chat-face {
    margin-left: 0;
    margin-right: 20px;
  }
  .chat-box {
    max-width: calc(100% - 145px);
    margin-left: 10px;
    font-size: 15px;
  }
  .chat-one-mine .chat-box {
    margin-right: 10px;
  }
  .chat-sender {
    color: #888;
    font-size: 14px;
    margin-top: -4px;
    margin-bottom: 5px;
  }
  .chat-content {
    position: relative;
    background-color: #fff;
    border-radius: 5px;
    padding: 10px;
    .micon {
      margin-right: 10px;
      color: #666;
    }
  }
  .img-box {
    float: left;
    border-radius: 5px;
    width: 115px;
    height: 100px;
    overflow: hidden;
    .chat-img {
      // max-width: 50%;
      width: 115px;
      height: 100%;
    }
  }

  .chat-one-mine .img-box {
    float: right;
    border-radius: 5px;
    width: 115px;
    height: 100px;
    .chat-img {
      // max-width: 50%;

      width: 115px;
      height: 100%;
    }
  }
}
.chat-footer-box {
  box-sizing: border-box;
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  .usephoto-box {
    width: 80px;
  }
  .usephoto {
    width: 80px;
    height: 80px;
    border-radius: 5px;
  }
  .chat-footer {
    width: 100%;
    padding: 0 10px;
    height: 60px;
    background-color: #fff;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    //   justify-content: space-between;
    align-items: center;
    align-content: center;
    border-top: 1px solid #ddd;

    .msg-input {
      background-color: #f1f1f2;
      width: calc(100% - 136px);
      height: 35px;
      line-height: 35px;
      font-size: 15px;
      border-radius: 17.5px;
      padding: 0 10px;
    }
    .send-btn {
      height: 26px;
      line-height: 26px;
      width: 40px;
      text-align: center;
      background-color: green;
      color: #ffffff;
      border-radius: 6px;
    }
  }
}

.left_triangle {
  position: absolute;
  top: 10px;
  right: -5px;
  width: 0;
  height: 0;
  border-left: 5px solid #6ebe89;
  border-bottom: 5px solid transparent;
  border-top: 5px solid transparent;
}
.right_triangle {
  position: absolute;
  top: 10px;
  left: -5px;
  width: 0;
  height: 0;
  border-top: 5px solid transparent;
  border-bottom: 5px solid transparent;
  border-right: 5px solid #fff;
}
.rx-box {
  width: 190px;
  height: 110px;
  background-color: #fff;
  border-radius: 8px;
  padding: 5px 0 9px 15px;
  .left {
    width: 30px;
    height: 28px;
  }
}

.utils {
  border-top: 1px solid #cdcdcd;
  padding: 16px 0 0 35px;
  img {
    width: 28px;
    height: 28px;
  }
}
:deep(.el-textarea__inner) {
  border: none;
  height: 60px;
  resize: none;
  overflow-y: hidden;
  width: 100%;
}
.footer-btn {
  padding: 0 18px 18px 0;
}
</style>
